package com.framework.loippi.controller.api;

import com.framework.loippi.api.utils.ApiUtils;
import com.framework.loippi.api.utils.Xerror;
import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.dto.api.dto.MedicineOrderParam;
import com.framework.loippi.entity.OrderItem;
import com.framework.loippi.entity.TLogistics;
import com.framework.loippi.entity.TMedicine;
import com.framework.loippi.entity.TOrder;
import com.framework.loippi.express.ExpressService;
import com.framework.loippi.plugin.wxapppay.miniprogrampay.PayUtils;
import com.framework.loippi.service.*;
import com.framework.loippi.support.APIPrincipal;
import com.framework.loippi.utils.RandomUtils;
import com.framework.loippi.utils.StringUtils;
import io.swagger.annotations.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Author fsociety
 * @Date 28/12/2019 下午12:13
 * @Version 1.0
 */

@Controller("apiOrderController")
@RequestMapping("/api/order")
@Api(tags = {"订单相关信息"})
public class OrderController extends ApiBaseController {

    @Resource
    private TOrderService orderService;
    @Resource
    private TLogisticsService logisticsService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private TMedicineService tMedicineService;
    @Resource
    private TUserService tUserService;
    @Resource
    private TLogisticsService tLogisticsService;
    @Resource
    private ExpressService expressService;

    @RequestMapping(value = "/generate.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "生成订单", notes = "{}")
    @Transactional(rollbackFor = Exception.class) //事务控制
    public @ResponseBody
    String generateOrder(Long userId, String orderName, String orderPhone, String orderAddress, String goodsArr, HttpServletRequest request) {
        //生成订单编号
        TOrder order = new TOrder();
        order.setOrderSn("yz" + System.currentTimeMillis());
        order.setUserName(orderName);
        order.setPhone(orderPhone);
        order.setUserId(userId);
        orderService.save(order);

        JSONArray array = JSONArray.fromObject(goodsArr);
        for (Object o : array) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            JSONObject json = (JSONObject) o;
            orderItem.setMedicineId(json.getLong("goodsId"));
            TMedicine medicine = tMedicineService.find(json.getLong("goodsId"));
            orderItem.setAmount(new BigDecimal(json.getDouble("money")));
            orderItem.setMedicineCount(json.getInt("goodsNum"));
            orderItem.setThumbnailPic(medicine.getThumbnailPic());
            orderItemService.save(orderItem);
        }


        return ApiUtils.success();
    }

    @RequestMapping(value = "findAllByUserId.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("查询用户所有订单")
    public @ResponseBody
    String findAllByUserId(Long userId, Integer currentPage) {
        Map<String, Object> param = new HashMap<>();
        int pageSize = 5;
        int cur = (currentPage - 1) * pageSize;
        param.put("pageNumber", cur);
        param.put("pageSize", pageSize);
        Map<String, Object> map = new HashMap<>();
        param.put("userId", userId);
        List<TOrder> orders = orderService.findAllByUserId(userId, cur, pageSize);
//      List<TOrder> orders = orderService.findListByPage(param);
        Long total = orderService.count(param);
        map.put("orders", orders);
        map.put("total", total);

        return ApiUtils.success(map);
    }

    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/cancelOrder.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "取消订单", notes = "{}")
    public @ResponseBody
    String cancelOrder(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        if (orderId != null) {
            map.put("orderId", orderId);
            TOrder tOrder = orderService.findDetailById(orderId);
            tOrder.setId(orderId);
            tOrder.setOrderStatus(-1); //订单状态为取消
            List<OrderItem> items = tOrder.getItems();
            for (OrderItem oi : items) {
                TMedicine medicine = tMedicineService.find(oi.getMedicineId());
                if (medicine.getSellcount() == null || medicine.getSellcount() == 0) {
                    medicine.setSellcount(0);
                    medicine.setRepertory(medicine.getRepertory() + oi.getMedicineCount());
                } else {
                    medicine.setSellcount(medicine.getSellcount() - oi.getMedicineCount());
                    medicine.setRepertory(medicine.getRepertory() + oi.getMedicineCount());
                }
                tMedicineService.update(medicine);
            }
            Long result = orderService.update(tOrder);

            // 取消订单的同时，如果有物流信息同时把物流信息设置为取消
            List<TLogistics> tLogistics = tLogisticsService.findByOrderId(tOrder.getId());
            if (tLogistics.size() > 0) {
                for (TLogistics tl : tLogistics) {
                    tl.setLogisticsState(4);
                }
            }
        }

        return ApiUtils.success();
    }

    @RequestMapping(value = "/payOrder.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "公众号/微信支付", notes = "返回微信字符串", produces = "application/json")
    @ApiResponses({
            @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败"),
            @ApiResponse(code = 10003, message = "参数错误")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authentication", value = "鉴权码", required = true, paramType = "header"),
            @ApiImplicitParam(name = "goodsArr", value = "商品 json 字符串", paramType = "query"),
    })
    public @ResponseBody
    String payOrder(String orderAddress, String orderPhone, String orderName, Long recommendId, @RequestParam(value = "goodsArr", required = false) String goodsArr, HttpServletRequest request) throws Exception {
        synchronized (this) {

//      todo
//  1. 解析 goodsObj 字符串，生成订单
            JSONArray jsonArray = JSONArray.fromObject(goodsArr);
            MedicineOrderParam param = new MedicineOrderParam();
            param.setMedicines(jsonArray);
            param.setUserAddress(orderAddress);
            param.setUserPhone(orderPhone);
            param.setUserName(orderName);
            param.setRecommendId(recommendId);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                Long medicineId = json.getLong("id");
                Integer medicineNum = json.getInt("num");
                TMedicine medicine = null;
                if (!StringUtils.isNullOrEmpty(medicineId)) {
                    medicine = tMedicineService.find(medicineId);
                }
                if (StringUtils.isNullOrEmpty(medicine)) {
                    return ApiUtils.error(Xerror.OBJECT_IS_NOT_EXIST, "商品不存在");
                }
                if (medicineNum < 0) {
                    return ApiUtils.error(Xerror.PARAM_INVALID, "参数错误");
                }
                if (medicine.getRepertory().compareTo(medicineNum) < 0) {
                    return ApiUtils.error(Xerror.MORE_THAN_REPERTORY, medicine.getName() + "商品库存不足");
                }
            }

//  2.计算价格，total_fee 要是整数，分为单位
            APIPrincipal principal = getPrincipal(request);
            System.out.println(principal.toString());
            String orderId = orderService.buildOrderId(param, principal);
//      TOrder order = new TOrder();
//      order.setId(Long.valueOf(orderId));
//      order.setAddressDetail(userAddress);
//      order.setPhone(userPhone);
//      TUser tUser = tUserService.find("openId", principal.getOpenId());
//      order.setUserId(tUser.getId());
//      Map map = WechatShareUtil.jsApiPay(principal.getOpenId(), total_fee, orderId,request);
            BigDecimal amount = orderService.find(Long.valueOf(orderId)).getAmount().multiply(BigDecimal.valueOf(100));
            String total_fee = amount.intValue()+"";
//            String total_fee = "1";
            String notify_url = "/api/payCallBack/orderpay/" + 1 + "/" + orderId + ".json";
            String randomString = "yz" + RandomUtils.getRandomNumberString(3) + orderId;
            Map<String, Object> map = PayUtils.wxPublicAppPay(principal.getOpenId(), orderId, randomString, Integer.valueOf(total_fee), notify_url, request);
            return ApiUtils.success(map);
        }

    }

    @RequestMapping(value = "/payFor.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("去付款")
    public @ResponseBody
    String payFor(Long orderId, HttpServletRequest request) {
        APIPrincipal principal = getPrincipal(request);
        String notify_url = "/api/payCallBack/orderpay/" + 1 + "/" + orderId + ".json";
//    真实价格,上线后恢复
//      String total_fee = orderService.find(orderId).getAmount().toString();
        String total_fee = "1";
        Map<String, Object> map = PayUtils.wxPublicAppPay(principal.getOpenId(), "ynyz" + orderId
                , "ynyz" + orderId.toString(), Integer.valueOf(total_fee), notify_url, request);
        return ApiUtils.success(map);
    }

    //登陆信息获取
    private APIPrincipal getPrincipal(HttpServletRequest request) {
        HttpSession session = request.getSession();
        APIPrincipal principal = (APIPrincipal) session.getAttribute(APIPrincipal.PREFIX_USER_SESSION);
        return principal;
    }

    @RequestMapping(value = "/findLogistics.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询物流信息", notes = "{}")
    public @ResponseBody
    String findLogistics(Long orderId) {
        logisticsService.findByOrderId(orderId);
        return ApiUtils.success();
    }

    @RequestMapping(value = "findDetail.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("查询订单详情")
    public @ResponseBody
    String findDetail(Long orderId) {
        TOrder order = orderService.findDetailById(orderId);
        // 快递100信息
        String key = ConfigCache.getConfig("express.100.key");
        String customer = ConfigCache.getConfig("express.100.customer");
        String secret = ConfigCache.getConfig("express.100.secret");
        String userId = ConfigCache.getConfig("express.100.userid");
        if (null != order.getLogisticsCompany() && null != order.getLogisticsNumber()) {
            // 快递公司编号
            String expressCompany = order.getLogisticsCompany();
            // 订单编号
            String orderNum = order.getLogisticsNumber();
            // 手机号码后四位
            String phone = order.getPhone().substring(order.getPhone().length() - 4);
            String from = "";                //出发地
            String to = "";                    //目的地
            int resultv2 = 0;                //开启行政规划解析

            ExpressService expressService = new ExpressService(key, customer);
            String result = expressService.synQueryData(expressCompany, orderNum, phone, from, to, resultv2);
            JSONObject json = JSONObject.fromObject(result);
            System.out.println(json);
            JSONArray jsonArray = json.getJSONArray("data");
            System.out.println(jsonArray.get(0));
            JSONObject logisticsJson = jsonArray.getJSONObject(0);
            order.setLogisticsContent(logisticsJson.getString("context"));
            if (json.getString("state").equals("0")) {
                order.setOrderStatus(1);
            }
            if (json.getString("state").equals("1")) {
                order.setOrderStatus(2);
            }
            if (json.getString("state").equals("3")) {
                order.setOrderStatus(5);
            }

            switch (order.getLogisticsCompany()) {
                case "zhongtong":
                    order.setLogisticsCompany("中通快递");
                    break;
                case "shunfeng":
                    order.setLogisticsCompany("顺风速运");
                    break;
                case "yunda":
                    order.setLogisticsCompany("韵达快递");
                    break;
                case "shentong":
                    order.setLogisticsCompany("申通快递");
                    break;
                case "yuantong":
                    order.setLogisticsCompany("圆通速递");
                    break;
                case "huitongkuaidi":
                    order.setLogisticsCompany("百世快递");
                    break;
                case "debangkuaidi":
                    order.setLogisticsCompany("德邦快递");
                    break;
                case "youzhengguonei":
                    order.setLogisticsCompany("邮政快递包裹");
                    break;
                case "tiantian":
                    order.setLogisticsCompany("天天快递");
                    break;

            }

        }

        return ApiUtils.success(order);
    }

    @RequestMapping(value = "/confirmReceive.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("确认收货")
    public @ResponseBody
    String confirmReceive(Long orderId) {
        TOrder order = new TOrder();
        order.setId(orderId);
        order.setOrderStatus(5);
        order.setReceiveTime(new Date());
        orderService.update(order);

        return ApiUtils.success();
    }


}
